/**
 * common.js
 * 业务无关的公共方法
 * 任何项目都能共用
 */

(function ($) {
    var updateDisabled = true;
    $.common = {};

    /**
     * 判断是否为空
     * @param param
     * @returns {boolean}
     */
    $.common.getUrlParam = function (name) {
        var url = window.location.href;
        var prefix = window.location.origin + window.location.pathname;
        url = url.replace(prefix, '');
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = url.substr(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        }
        return null;
    };

    $.common.getUrlAllParams = function () {
        let params = {};
        window.location.search.slice(1).split('&').forEach(elm => {
            if (elm === '') return;
            let spl = elm.split('=');
            const d = decodeURIComponent;
            params[d(spl[0])] = (spl.length >= 2 ? d(spl[1]) : true);
        });

        return params;
    };


    $.common.proecessAjaxSuccess = function (paramJsonObj, alertdiv, gridDivId, systemparam_selectedIds) {

        if ("-1" == paramJsonObj.status) {
            this.showErrorMessage(paramJsonObj.returnMsg)
        } else {
            this.showSuccessMessage(paramJsonObj.returnMsg)
        }
    };

    $.common.proecessAjaxError = function (xmlR, status, e, alertdiv, gridDivId, systemparam_selectedIds) {
        var showMsgOpt = {
            showMsgId: alertdiv,
            status: xmlR.status,
            showMsg: xmlR.responseText
        };
        this.showErrorMessage(xmlR.status + ":" + xmlR.responseText)
    };

    $.common.showSuccessMessage = function (message) {
        layer.msg(message, {icon: 1, time: 1 * 1000, closeBtn: 1, offset: '50px'});
    }
    $.common.showErrorMessage = function (message) {
        layer.msg(message, {icon: 2, time: 60 * 60 * 1000, closeBtn: 1, offset: '50px'});
    }
    /**
     * 1成功
     * 2失败
     * */
    $.common.showMessageNoBtn = function (type, message) {
        layer.msg(message, {icon: type, time: 5 * 1000, closeBtn: 0, offset: '15rem'});
    }
    /**
     * 设置当前用户
     * @param data
     */
    $.common.setUserInfo = function (data) {
        if (0 == data.powerDataType) {
            updateDisabled = false
        }
        if (typeof (Storage) !== "undefined") {
            localStorage.setItem("userInfo", JSON.stringify(data));
        }
    }
    /**
     * 获取当前用户
     */
    $.common.getUserInfo = function () {
        if (typeof (Storage) !== "undefined") {
            let item = localStorage.getItem("userInfo");
            return JSON.parse(item);
        } else {
            return undefined;
        }
    }
    $.common.checkUserAdmin = function () {
        if (typeof (Storage) !== "undefined") {
            let item = localStorage.getItem("userInfo");
            let user = JSON.parse(item);
            if ("admin" == user.userName) {
                return true;
            }
        }
        return false;
    }

    $.common.userIsAdmin = function () {
        let roleType = $.common.getUserInfo().roleType;
        return roleType != 0 ? true : false;
    }

    /**
     * 权限数据是否能查看
     * @returns {boolean}
     */
    $.common.userIsShowPower = function () {
        let powerDataType = $.common.getUserInfo().powerDataType;
        return powerDataType != 2 ? true : false;
    }
})(jQuery);
(function ($) {
    $.utils = {};
    /**
     * 长度单位换算  厘米换算英寸
     * @param param
     * @returns {boolean}
     */
    $.utils.lengthConversion = function (para) {
        if (typeof para == 'number') {
            let i = para / 2.54
            i = i.toFixed(2)
            return para + "cm  |  " + i + "in";
        }
    }
    $.utils.getIds = function (para) {
        let arr = new Array();
        for (let i in para) {
            arr.push(para[i].id);
        }
        return arr;
    }
})(jQuery);
(function ($) {
    $.extend({

        /**
         * 自定义AJAX
         * @param url   请求路径
         * @param type  请求类型[如get/post等]
         * * @param data 数据
         * @param async 是否同步
         * @param dataType  数据类型,默认json
         * @param successCallback 成功回调
         * @param errorCallback 失败回调
         * @constructor
         */
        xAjax: function (url, type, data, callBackFunct, async, dataType, contentType) {
            var result = null;
            if (!dataType) {
                dataType = 'json';
            }
            if (!async) {
                async = false;
            }
            if (!contentType) {
                contentType = "application/json; charset=utf-8";
            }
            $.ajax({
                url: url,
                dataType: dataType,
                type: type,
                async: async,
                data: data,
                processData: false, // 使数据不做处理
                contentType: contentType, // 不要设置Content-Type请求头
                success: function (jsonData) { //请求成功的操作
                    result = jsonData;
                    if ("-414" == result.code) {
                        window.location.href = "/loginPage";
                    }
                    if (callBackFunct) {
                        if (callBackFunct.onSuccess) {
                            callBackFunct.onSuccess(jsonData);
                        }
                    }
                },
                error: function (xmlR, status, e) {
                    // if (callBackFunct) {
                    //     if (callBackFunct.onError) {
                    //         callBackFunct.onError(xmlR, status, e);
                    //     }
                    // }else{
                    //     $.common.showSuccessMessage(e);
                    // }
                },
                beforeSend: function () { //请求前的操作
                    // if(callBackFunct){
                    //     if (callBackFunct.beforeSend) {
                    //         callBackFunct.beforeSend();
                    //     }
                    // }
                },
                complete: function () { //完成后的操作
                    // if(callBackFunct){
                    //     if (callBackFunct.complete) {
                    //         callBackFunct.complete();
                    //     }
                    // }
                }
            });
            return result;
        }
    });
})(jQuery);

(function ($) {
    $.extend({
        ajaxDocument: function (option) {
            /**
             * option：配置项
             *  {
             *     url,地址
             *     type, 请求类型ＰＯＳＴ，ＧＥＴ

             *     header，请求头token等设置
             *     param 参数
             *
             *  }
             */
            if (!option) {
                throw "param is error or NULL!";
            }
            if (!option.url) {
                throw "url is NULL or length=0!";
            }
            if (!option.type) {
                throw "type is NULL!";
            }

            const promise = new Promise(function (resolve, reject) {
                const handler = function () {
                    if (4 !== this.readyState) {
                        return false;
                    }
                    if (200 === this.status) {
                        resolve(this.response);
                    } else {
                        reject(new Error(this.statusText));
                    }
                };
                const client = new XMLHttpRequest();
                client.open(option.type, option.url, true);
                client.onreadystatechange = handler;
                client.responseType = "blob";

                if (option.header) {
                    for (key in option.header) {
                        client.setRequestHeader(key, option.header[key]);
                    }
                }
                client.send(option.param);

            });
            return promise;
        }

    });
})(jQuery);

